﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using GheSofa.Models;

namespace GheSofa.Models
{
    public class CartIndexViewModel
    {
        public Cart Cart { get; set; }
    }
    public class Cart
    {
        private GheSofaEntities db = new GheSofaEntities();
        public List<CartLine> dssanpham = new List<CartLine>();

        public void AddItem(string Masp, string Tensp, int Giasanpham, int quantity)
        {
            CartLine line = dssanpham.Where(p => p.masp == Masp).FirstOrDefault();
            if (line == null)
            {
                dssanpham.Add(new CartLine { masp = Masp, tensp = Tensp, giasanpham = Giasanpham, Quantity = quantity });
            }
            else
            {
                line.Quantity += quantity;
            }
        }
        public void RemoveLine(string masp)
        {
            dssanpham.RemoveAll(l => l.masp.Trim() == masp);
        }
        public decimal tongtien()
        {
            return dssanpham.Sum(e => e.giasanpham * e.Quantity);
        }
        public void capnhatsoluong(string masp, int soluong)
        {
            CartLine line = dssanpham.Where(p => p.masp == masp).FirstOrDefault();
            line.Quantity = soluong;
        }
        public void Clear()
        {
            dssanpham.Clear();
        }
        public decimal tongsanpham()
        {
            return dssanpham.Sum(e => e.Quantity);
        }
        public IEnumerable<CartLine> Lines
        {
            get { return dssanpham; }
        }

        public void save(HoaDon hd)
        {
            List<ChiTietHoaDon> dsctdh = db.ChiTietHoaDons.ToList();
            db.HoaDons.Add(hd);
            db.SaveChanges();
            foreach (var item in dssanpham)
            {
                ChiTietHoaDon cthd = new ChiTietHoaDon();
                cthd.MaHD = hd.MaHD;
                cthd.MaSP = item.masp;
                cthd.SoLuong = item.Quantity;
                cthd.Gia = item.giasanpham;
                db.ChiTietHoaDons.Add(cthd);
            }
            db.SaveChanges();
        }
    }
    public class CartLine
    {
        public string masp { get; set; }
        public string tensp { get; set; }
        public int giasanpham { get; set; }
        public int Quantity { get; set; }
    }

}
